package com.randb.easyhttp.subscriber;

import android.annotation.SuppressLint;
import android.content.Context;
import android.text.TextUtils;

import com.randb.easyhttp.callback.Callback;
import com.randb.easyhttp.callback.DownProgressCallback;
import com.randb.easyhttp.exception.ApiException;
import com.randb.easyhttp.utils.HttpLog;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import okhttp3.ResponseBody;

/**
 * User: RandBII
 * Date: 2020/5/11
 * Description:
 */
public class DownloadSubscriber<T extends ResponseBody> extends BaseSubscriber<T> {

    private Context context;
    private String path;
    private String name;
    public Callback mCallback;
    private static String APK_CONTENT_TYPE = "application/vnd.android.package-archive";
    private static String PNG_CONTENT_TYPE = "image/png";
    private static String JPG_CONTENT_TYPE = "image/jpg";
    private static String fileSuffix = "";
    private long lastRefreshUiTime;

    public DownloadSubscriber(Context context, String path, String name, Callback callback) {
        this.context = context;
        this.path = path;
        this.name = name;
        this.mCallback = callback;
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (mCallback != null) {
            mCallback.onStart();
        }
    }


    @Override
    public void onError(ApiException e) {

    }

    @Override
    public void onComplete() {

    }

    @Override
    public void onNext(T t) {
        super.onNext(t);
        writeResponseBodyToDisk(path, name, context, t);
    }

    @SuppressLint("CheckResult")
    private void writeResponseBodyToDisk(String path, String name, Context context, ResponseBody body) {

        if (!TextUtils.isEmpty(name)) {//text/html; charset=utf-8
            String type;
            if (!name.contains(".")) {
                type = Objects.requireNonNull(body.contentType()).toString();
                if (type.equals(APK_CONTENT_TYPE)) {
                    fileSuffix = ".apk";
                } else if (type.equals(PNG_CONTENT_TYPE)) {
                    fileSuffix = ".png";
                } else if (type.equals(JPG_CONTENT_TYPE)) {
                    fileSuffix = ".jpg";
                } else {
                    fileSuffix = "." + body.contentType().subtype();
                }
                name = name + fileSuffix;
            }
        } else {
            name = System.currentTimeMillis() + fileSuffix;
        }

        if (path == null) {
            path = context.getExternalFilesDir(null) + File.separator + name;
        } else {
            File file = new File(path);
            if (!file.exists()) {
                file.mkdirs();
            }
            path = path + File.separator + name;
            path = path.replaceAll("//", "/");
        }

        try {
            File futureStudioIconFile = new File(path);
           /* if (!futureStudioIconFile.exists()) {
                futureStudioIconFile.createNewFile();
            }*/
            InputStream inputStream = null;
            FileOutputStream outputStream = null;
            try {
                //byte[] fileReader = new byte[2048];
                byte[] fileReader = new byte[1024 * 128];

                final long fileSize = body.contentLength();
                long fileSizeDownloaded = 0;
                HttpLog.d("file length: " + fileSize);
                inputStream = body.byteStream();
                outputStream = new FileOutputStream(futureStudioIconFile);
                final Callback callBack = mCallback;
                while (true) {
                    int read = inputStream.read(fileReader);

                    if (read == -1) {
                        break;
                    }

                    outputStream.write(fileReader, 0, read);
                    fileSizeDownloaded += read;
                    HttpLog.i("file download: " + fileSizeDownloaded + " of " + fileSize);
                    //下载进度
                    float progress = fileSizeDownloaded * 1.0f / fileSize;
                    long curTime = System.currentTimeMillis();
                    //每200毫秒刷新一次数据,防止频繁更新进度
                    if (curTime - lastRefreshUiTime >= 200 || progress == 1.0f) {
                        if (callBack != null) {
                            if (callBack != null) {
                                final long finalFileSizeDownloaded = fileSizeDownloaded;
                                Observable.just(finalFileSizeDownloaded)
                                        .observeOn(AndroidSchedulers.mainThread())
                                        .subscribe(new Consumer<Long>() {
                                            @Override
                                            public void accept(@NonNull Long aLong) throws Exception {
                                                if (callBack instanceof DownProgressCallback) {
                                                    ((DownProgressCallback) callBack).update(finalFileSizeDownloaded, fileSize, finalFileSizeDownloaded == fileSize);
                                                }
                                            }
                                        }, new Consumer<Throwable>() {
                                            @Override
                                            public void accept(@NonNull Throwable throwable) throws Exception {

                                            }
                                        });
                            }
                        }
                        lastRefreshUiTime = System.currentTimeMillis();
                    }
                }

                outputStream.flush();
                HttpLog.i("file downloaded: " + fileSizeDownloaded + " of " + fileSize);

                if (callBack != null) {
                    //final String finalName = name;
                    final String finalPath = path;
                    Observable.just(finalPath)
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new Consumer<String>() {
                                @Override
                                public void accept(@NonNull String s) throws Exception {
                                    if (callBack instanceof DownProgressCallback) {
                                        ((DownProgressCallback) callBack).onComplete(finalPath);
                                    }
                                }
                            }, new Consumer<Throwable>() {
                                @Override
                                public void accept(@NonNull Throwable throwable) throws Exception {

                                }
                            });
                    HttpLog.i("file downloaded: " + fileSizeDownloaded + " of " + fileSize);
                    HttpLog.i("file downloaded: is sucess");
                }

            } catch (IOException e) {
                finalonError(e);

            } finally {
                if (outputStream != null) {
                    outputStream.close();
                }

                if (inputStream != null) {
                    inputStream.close();
                }
            }
        } catch (IOException e) {
            finalonError(e);
        }


    }

    @SuppressLint("CheckResult")
    private void finalonError(final Exception e) {

        if (mCallback == null) {
            return;
        }
        //if (Utils.checkMain()) {
        Observable.just(new ApiException(e, 100))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<ApiException>() {
                    @Override
                    public void accept(@NonNull ApiException e) throws Exception {
                        if (mCallback != null) {
                            mCallback.onError(e);
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(@NonNull Throwable throwable) throws Exception {

                    }
                });
    }
}
